#include "Channel.hpp"
#include "EventLoop.hpp" // 需要你自己实现 EventLoop

#include <unistd.h>

Channel::Channel(EventLoop* loop, int fd)
    : loop_(loop),
      fd_(fd),
      events_(0),
      revents_(0),
      index_(-1) {}

Channel::~Channel() {}

void Channel::handleEvent() {
    if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN)) {
        if (closeCallback_) closeCallback_();
    }
    if (revents_ & EPOLLERR) {
        if (errorCallback_) errorCallback_();
    }
    if (revents_ & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) {
        if (readCallback_) readCallback_();
    }
    if (revents_ & EPOLLOUT) {
        if (writeCallback_) writeCallback_();
    }
}

void Channel::setReadCallback(const EventCallback& cb) {
    readCallback_ = cb;
}

void Channel::setWriteCallback(const EventCallback& cb) {
    writeCallback_ = cb;
}

void Channel::setCloseCallback(const EventCallback& cb) {
    closeCallback_ = cb;
}

void Channel::setErrorCallback(const EventCallback& cb) {
    errorCallback_ = cb;
}

void Channel::setAnythingCallback(const EventCallback& cb){
    anythingCallback_= cb;
}

void Channel::enableReading() {
    events_ |= EPOLLIN;
    update();
}

void Channel::enableWriting() {
    events_ |= EPOLLOUT;
    update();
}

void Channel::disableWriting() {
    events_ &= ~EPOLLOUT;
    update();
}

void Channel::disableAll() {
    events_ = 0;
    update();
}

bool Channel::isWriting() const {
    return events_ & EPOLLOUT;
}

int Channel::getFd() const {
    return fd_;
}

int Channel::getEvents() const {
    return events_;
}

void Channel::setRevents(int revt) {
    revents_ = revt;
}

int Channel::index() const {
    return index_;
}

void Channel::setIndex(int idx) {
    index_ = idx;
}

EventLoop* Channel::ownerLoop() {
    return loop_;
}

void Channel::update() {
    // 通知 EventLoop 更新 poller 中的事件
    // 实际依赖于 EventLoop 实现的 updateChannel 方法
    if (loop_) {
        loop_->updateChannel(this);
    }
}
